const multer = require("multer");
const path = require("path");
const fs = require("fs");
const TaskAttachment = require("../models/TaskAttachment");

// 确保上传目录存在
const uploadDir = path.join(__dirname, "../../uploads");
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 按日期创建子目录
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");

    const uploadPath = path.join(uploadDir, year.toString(), month, day);

    // 确保目录存在
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }

    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名：时间戳_随机数_原文件名
    const timestamp = Date.now();
    const random = Math.round(Math.random() * 1e9);
    const ext = path.extname(file.originalname);
    const name = path.basename(file.originalname, ext);

    // 清理文件名，只保留字母数字和连字符
    const cleanName = name.replace(/[^a-zA-Z0-9\u4e00-\u9fa5-_]/g, "_");
    const fileName = `${timestamp}_${random}_${cleanName}${ext}`;

    cb(null, fileName);
  },
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 允许的文件类型
  const allowedMimes = [
    // 图片
    "image/jpeg",
    "image/jpg",
    "image/png",
    "image/gif",
    "image/bmp",
    "image/webp",
    "image/svg+xml",
    // 文档
    "application/pdf",
    "application/msword",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.ms-powerpoint",
    "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    "text/plain",
    "text/rtf",
    // 压缩文件
    "application/zip",
    "application/x-rar-compressed",
    "application/x-7z-compressed",
    "application/x-tar",
    "application/gzip",
    // 视频
    "video/mp4",
    "video/avi",
    "video/quicktime",
    "video/x-msvideo",
    "video/webm",
    // 音频
    "audio/mpeg",
    "audio/wav",
    "audio/flac",
    "audio/aac",
    "audio/ogg",
  ];

  if (allowedMimes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error(`不支持的文件类型: ${file.mimetype}`), false);
  }
};

// 创建multer实例
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 50 * 1024 * 1024, // 50MB限制
    files: 10, // 最多10个文件
  },
});

// 错误处理中间件
const handleUploadError = (err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    if (err.code === "LIMIT_FILE_SIZE") {
      return res.status(400).json({ message: "文件大小超过限制（最大50MB）" });
    }
    if (err.code === "LIMIT_FILE_COUNT") {
      return res.status(400).json({ message: "文件数量超过限制（最多10个）" });
    }
    if (err.code === "LIMIT_UNEXPECTED_FILE") {
      return res.status(400).json({ message: "意外的文件字段" });
    }
  }

  if (err.message.includes("不支持的文件类型")) {
    return res.status(400).json({ message: err.message });
  }

  next(err);
};

// 单文件上传中间件
const uploadSingle = (fieldName) => [
  upload.single(fieldName),
  handleUploadError,
];

// 多文件上传中间件
const uploadMultiple = (fieldName, maxCount = 10) => [
  upload.array(fieldName, maxCount),
  handleUploadError,
];

// 清理临时文件
const cleanupTempFiles = (req, res, next) => {
  // 如果请求失败，清理已上传的文件
  const originalSend = res.send;
  res.send = function (data) {
    if (res.statusCode >= 400 && req.file) {
      const filePath = req.file.path;
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    }
    originalSend.call(this, data);
  };
  next();
};

module.exports = {
  upload,
  uploadSingle,
  uploadMultiple,
  handleUploadError,
  cleanupTempFiles,
};
